package com.chunuo.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chunuo.eduservice.entity.EduVideo;
import com.chunuo.eduservice.mapper.EduVideoMapper;
import com.chunuo.eduservice.openfeign.EduVideoOpenFeign;
import com.chunuo.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-04
 */
@Slf4j
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private EduVideoOpenFeign eduVideoOpenFeign;

    /**
     * 删除课程下的所有小节
     * @param id
     */
    @Override
    public void delete(String id) {
        //查询课程下的所有 视频id
        List<EduVideo> list = this.list(new QueryWrapper<EduVideo>().eq("course_id", id).select("video_source_id"));
        log.info("list = {}",list);
        List<String> ids = new ArrayList<>();
        for(EduVideo entity:list){
            //视频id 封装到list中
            if(!org.springframework.util.StringUtils.isEmpty(entity.getVideoSourceId()))
                ids.add(entity.getVideoSourceId());
        }
        log.info("ids = {}",ids);
        //得到  "id1,id2,id3" 为了满足删除视频的参数需求
        if(ids.size()>0){
            StringBuffer videoSourceIds = new StringBuffer();
            for(int i = 0;i<ids.size();i++){
                if(i+1==ids.size()){
                    videoSourceIds.append(ids.get(i));
                }else{
                    videoSourceIds.append(ids.get(i)+",");
                }
            }
            eduVideoOpenFeign.removeCourseVideo(videoSourceIds.toString());
        }

        this.remove(new QueryWrapper<EduVideo>().eq("course_id",id));
    }

    /**
     * 删除指定的小节
     * @param id
     */
    @Override
    public void deleteVideo(String id) {
        EduVideo video = this.getById(id);
        String videoSourceId = video.getVideoSourceId();
        //远程调用删除视频方法
        eduVideoOpenFeign.removeAlyVideo(videoSourceId);
        //删除小节
        this.removeById(id);
    }

//
//    public static void main(String[] args) {
//        List<String> ids = new ArrayList();
//        ids.add("a");
//        ids.add("b");
//        StringBuffer videoSourceIds = new StringBuffer();
//        for(int i = 0;i<ids.size();i++){
//            if(i+1==ids.size()){
//                videoSourceIds.append(ids.get(i));
//            }else{
//                videoSourceIds.append(ids.get(i)+",");
//            }
//        }
//        System.out.println(videoSourceIds);
//    }

}
